package com.cgs.query.handler.render

import com.cgs.query.domain.BoundSql
import com.cgs.query.domain.ExecutionObj
import com.cgs.query.domain.ParameterMapping
import com.cgs.query.exception.QueryException
import com.cgs.query.handler.ParameterHandler
import com.cgs.query.util.Utils


/**
 * ?号渲染
 */
class QMakeParameterHandler : ParameterHandler {

    override fun resolve(executionObj: ExecutionObj, param: Map<String, Any?>): BoundSql {
        checkParameterCount(executionObj.statement, param)
        return BoundSql(executionObj.statement, param.map {
            ParameterMapping(it.key, it.value
                    ?: throw QueryException("参数:${it.key}不能为Null"))
        }.toList())
    }


    private fun checkParameterCount(statement: String, param: Map<String, Any?>) {
        Utils.trueAndThen(statement.count { '?' == it } != param.size) {
            throw QueryException("参数数量不匹配")
        }
    }
}